import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Input,
    Button,
    notification,
    Radio,
    Modal,
    Upload,
    Tooltip,
    Collapse,
    InputNumber,
    Select,
} from 'antd';
import { addWordvecs, editWordvecs, getAlgorithms, getWordvecsList } from '@/services/resource';
import Styles from '../../style.less'
import { baseUrl } from '@/utils/config.js'
import { checkBeforeFileUpload } from '@/utils/utils'

const { Option } = Select;
const { Panel } = Collapse;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
    },
};


class Edit extends React.Component {
    constructor(argus) {
        super(argus);

        this.state = {
            fileList: [], // 上传文件成员
            sourceType: '',//  训练类型 0 上传-词向量 1 训练-语料
            loading: false,
            algorithms: [],
            highConfig: [],
        };
    }

    componentDidMount() {
        this.queryAlgorithms();
    }
    // 获取算法
    queryAlgorithms() {
        getAlgorithms().then(res => {
            if (res.retCode === '0') this.setState({ algorithms: res.data, })
        })
    }
    // 训练类型
    filesType = e => {
        this.setState({
            sourceType: e.target.value,
        });
    }

    // 名称校验
    onNameBlur = e => {
        const wordvecNameStrict = e.target.value;
        wordvecNameStrict && getWordvecsList({ wordvecNameStrict }).then(res => {
            if (res.retCode === '0') {
                if (res.data.length > 0) {
                    this.props.form.setFields({
                        wordvecName: {
                            value: wordvecNameStrict,
                            errors: [new Error('名称已存在!')],
                        },
                    });
                    return;
                }
            }
        })
    }

    // 选中的算法 id
    onAlgorithmChange(algorithm_id) {
        const { algorithms } = this.state;
        let highConfig;
        algorithms.map(val => {
            if (val.id === algorithm_id) {
                highConfig = val.parameters
            }
        })
        this.setState({ highConfig });
    }

    infoToParent(key) {
        this.props.callBack(key);
    }

    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        const { sourceType, fileList } = this.state;
        const { form, wordvecId, wordvecName } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                const formData = new FormData();
                if (fileList.length == 0 && sourceType == 0 && !Boolean(wordvecName)) {
                    _this.props.form.setFields({
                        files: {
                            errors: [new Error('请上传文件!')],
                        },
                    });
                    return;
                }
                if (sourceType == 0) { // 添加词向量,使用已训练好的词向量文件
                    fileList.forEach(file => {
                        formData.append('file', file);
                    });
                    formData.append('modelWordvecName', values.wordvecName);
                    formData.append('sourceType', 0);
                }
                _this.setState({ loading: true, })
                addWordvecs(Boolean(wordvecName) ? { ...values, wordvecId } : (sourceType == 0 ? formData : { ...values, wordvecConfig: values }), sourceType, Boolean(wordvecName)).then(res => {
                    if (res.retCode == '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '词向量',
                            description: `${Boolean(wordvecName) ? '修改' : '添加'}词向量成功`,
                        });
                        _this.props.callBack(false);
                    } else { _this.setState({ loading: false, }) }
                })
            }
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { sourceType, loading, fileList, algorithms, algorithm_id, highConfig } = this.state;
        const { isShowAddWordvecModel, wordvecId, wordvecName } = this.props;
        const props = {
            multiple: false,
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file, fileLists) => {
                let find = fileList.find(item => item.name === file.name);
                let isAcceptFileType = checkBeforeFileUpload(file, ['txt', 'kv']);
                if (!isAcceptFileType.tip) {
                    notification['warning']({
                        message: '警告',
                        key: isAcceptFileType.msg,
                        description: isAcceptFileType.msg
                    });
                    return true;
                }
                if (find) {
                    notification['warning']({
                        message: '警告',
                        key: '存在同名文件',
                        description: '存在同名文件'
                    });
                    return true;
                } else {
                    if (fileLists.length > 5 - this.state.fileList.length) {
                        notification['warning']({
                            message: '警告',
                            key: '每次上传文件个数不超过5个',
                            description: '每次上传文件个数不超过5个'
                        });
                        return true;
                    } else {
                        this.setState(state => ({
                            fileList: [file],
                        }));
                        return false;
                    }
                }
            },
            fileList,
        };


        return (
            <Modal
                title={`${Boolean(wordvecName) ? '编辑' : '添加'}词向量`}
                maskClosable={false}
                visible={isShowAddWordvecModel}
                width={600}
                onCancel={this.infoToParent.bind(this, false)}
                footer={[
                    <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
                    <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
                ]}
            >
                <Form className={Styles.configForm}>
                    <Form.Item label="词向量名称" {...formItemLayout}>
                        {getFieldDecorator('wordvecName', {
                            rules: [{ required: true, pattern: /^[\u4e00-\u9fa5\w]{1,16}$/, message: '词向量名称不为空、不允许特殊字符且长度不超过16!' }],
                            initialValue: wordvecName || '',
                        })(
                            <Input placeholder="词向量名称" onBlur={this.onNameBlur.bind(this)} />
                        )}
                    </Form.Item>
                    {!Boolean(wordvecName) &&
                        <>
                            <Form.Item label="上传文件类型" {...formItemLayout} onChange={this.filesType.bind(this)}>
                                {getFieldDecorator('sourceType', {
                                    rules: [{ required: true }],
                                    initialValue: 0,
                                })(
                                    <Radio.Group>
                                        <Radio value={0} role={'上传'}>词向量</Radio>
                                        <Radio value={1} role={'训练'}>语料</Radio>
                                    </Radio.Group>,
                                )}
                            </Form.Item>
                            {sourceType == 1 ? <>
                                <Form.Item label="算法" {...formItemLayout}>
                                    {getFieldDecorator('algorithm_id', {
                                        rules: [{ required: true, message: '请选择算法!' }],
                                    })(
                                        <Select placeholder="请选择算法" showSearch onChange={this.onAlgorithmChange.bind(this)} filterOption={(input, option) =>
                                            option.props.children.join('').toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }>
                                            {
                                                algorithms.map(val => <Option key={val.id} value={val.id}>{val.algorithmName}</Option>)
                                            }
                                        </Select>
                                    )}
                                </Form.Item>
                                <Collapse expandIconPosition={'right'} bordered={false}>
                                    <Panel header={<span style={{ fontWeight: 700 }}>{'高级配置'}</span>} className={Styles.highConfig}>
                                        {
                                            highConfig.map((val, i) => <Form.Item key={i} label={val.paramLabel} {...formItemLayout}>
                                                {getFieldDecorator(val.paramName, {
                                                    rules: [{ required: true, message: `${val.paramLabel}不能为空!` }],
                                                    initialValue: val.value,
                                                })(
                                                    val.paramType == 'int' ? <InputNumber key={i} min={val.range.from || 0} max={val.range.to || 10000} /> :
                                                        val.paramType == 'float' ? <InputNumber key={i} min={val.range.from || 0} max={val.range.to || 10000} step={0.01} /> :
                                                            val.paramType == 'enum' ? <Select
                                                                showSearch
                                                                style={{ width: 320 }}
                                                                placeholder={`请选择${val.paramLabel}`}
                                                                optionFilterProp="children"
                                                                filterOption={(input, option) =>
                                                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                }
                                                            >
                                                                {
                                                                    val.enumValues.map((v, i) => <Option key={i} value={v}>{val.paramName === "negativeUsed" ? ['否', '是'][v - 0] : v}</Option>)
                                                                }
                                                            </Select> :
                                                                <Select    //val.paramType == 'listbox'
                                                                    showSearch
                                                                    style={{ width: 320 }}
                                                                    optionFilterProp="children"
                                                                    placeholder={`请选择${val.paramLabel}`}
                                                                    filterOption={(input, option) =>
                                                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                                    }
                                                                >
                                                                    {
                                                                        wordvecs.map((val, i) => <Option key={i} value={val.wordvecId}>{val.wordvecName}</Option>)
                                                                    }
                                                                </Select>
                                                )}
                                            </Form.Item>)
                                        }
                                    </Panel>
                                </Collapse></>
                                :
                                <Form.Item label='上传文件' style={{ marginBottom: 0 }} {...formItemLayout}>
                                    <div className="dropbox">
                                        {getFieldDecorator('files', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请上传文件!',
                                                },
                                            ],
                                        })(
                                            <span>
                                                <Upload {...props} accept=".txt,.kv">
                                                    <Button size='small'> <UploadOutlined /> 点击上传 </Button>
                                                </Upload>
                                                <div style={{ padding: '6px 4px', backgroundColor: 'rgba(240, 242, 245, 1)', lineHeight: '24px', width: 360 }}>
                                                    <section>支持扩展名：.txt .kv</section>
                                                    <section>只能上传一个文件<a target='_blank' download={'模板'} className="ant-dropdown-link" type='link' href={baseUrl + '/templates/wordvec'}>下载示例模板</a></section>
                                                </div>
                                            </span>
                                        )}
                                    </div>
                                </Form.Item>
                            }
                        </>
                    }
                </Form>
            </Modal>
        );
    }
}

const AddWordvec = Form.create()(Edit);

export default AddWordvec;